package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdong.data.DataResult;
import com.dongdong.data.ResponseStatusEnum;
import com.dongdong.pojo.TbContent;
import com.dongdong.pojo.TbContentCategory;
import com.dongdong.service.ContentCategoryService;
import com.dongdong.service.ContentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/16 11:48
 * @Version 1.0
 **/
@Controller
@RequestMapping("contentController")
public class ContentController {

    private static final Logger logger = LoggerFactory.getLogger(ContentCategoryController.class);

    @Reference
    private ContentService contentService;

    @Reference
    private ContentCategoryService contentCategoryService;

    @RequestMapping("list")
    public String list(Model model){
        List<TbContentCategory> list = contentCategoryService.getContentC();
        model.addAttribute("cc",list);
        return "admin/content";
    }

    @RequestMapping("getContent")
    @ResponseBody
    public DataResult getContentCategory(){
        try {
            List<TbContent> list = contentService.getContentCategory();
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(list);
        }catch (Exception e){
            logger.error("查询错误");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("insertContent")
    @ResponseBody
    public DataResult insertContent(TbContent content){
        try {
            contentService.insertContent(content);
            return DataResult.response(ResponseStatusEnum.SUCCESS);
        }catch (Exception e){
            logger.error("增加错误");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("toUpdate/{id}")
    @ResponseBody
    public DataResult toUpdate(@PathVariable("id") Long id){
        try {
            TbContent content = contentService.toUpdate(id);
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(content);
        }catch (Exception e){
            logger.error("回显失败");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("updateContent")
    @ResponseBody
    public DataResult updateContent(TbContent content){
        try {
            contentService.updateContent(content);
            return DataResult.response(ResponseStatusEnum.SUCCESS);
        }catch (Exception e){
            logger.error("修改错误");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("deleteContent")
    @ResponseBody
    public DataResult deleteContent(@RequestParam("ids[]") Long[] ids){
        try {
            contentService.deleteContent(ids);
            return DataResult.response(ResponseStatusEnum.SUCCESS);
        }catch (Exception e){
            logger.error("删除错误");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("upLoadFile")
    @ResponseBody
    public DataResult upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile){
        try{
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-beijing.aliyuncs.com";
            String domain = "oss-cn-beijing.aliyuncs.com";
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "LTAI4G7eZ5SaEGucGGDSue4a";
            String accessKeySecret = "CCEA89SriqlLlytasVbZ4K11Xwi7ay";
            String bucketName = "l-h";
            // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = myFile.getOriginalFilename();//上传文件的路径

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            //String content = "Hello OSS";
            String url = null;//前台路径
            try {
                ossClient.putObject(bucketName, objectName, myFile.getInputStream());
                //拼接图片访问路径
                url = "http://" + bucketName +"."+ domain +"/"+objectName;
//                System.out.println(url);

            } catch (IOException e) {
                e.printStackTrace();
                return DataResult.response(ResponseStatusEnum.SUCCESS);
            }

            // 关闭OSSClient
            ossClient.shutdown();
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(url);
        }catch (Exception e){
            logger.info("操作异常",e);
            return DataResult.response(ResponseStatusEnum.SUCCESS);
        }
    }
}

